<template>
    <div class='competition-detail'>
        <!--        封面-->
        <div class='cover'>
            <img v-if='competition.cover' :src='`/api/${competition.cover}`' alt='background'>
            <img v-else src='@/assets/images/login-background.jpg' alt='background'>
        </div>
        <div class='content-main'>
            <!--        面包屑-->
            <div class='crumbs'>
                <breadcrumb id='breadcrumb-container' class='breadcrumb-container' />
            </div>
            <div class='competition-detail-content'>
                <div class='left'>
                    <div class='title'>{{ competition?.title || '比赛标题' }}</div>
                    <div class='icons'>
                        <div class='icon'><span>浏览</span><span>{{ handleCount(competition?.views || 0) }}</span></div>
                        <div class='icon'><span>收藏</span><span>{{ handleCount(competition?.collect || 0) }}</span>
                        </div>
                        <div class='icon'><span>评论</span><span>{{ 0 }}</span></div>
                    </div>
                    <div class='icons'>
                        <div class='icon date'>
                            <span>比赛时间</span><span>{{ parseTime(competition.startTime, '{y}/{m}/{d}')
                            }}-{{ parseTime(competition.endTime, '{y}/{m}/{d}') }}</span></div>
                        <div class='icon date'>
                            <span>报名时间</span><span>{{ parseTime(competition.signStartTime, '{y}/{m}/{d}')
                            }}-{{ parseTime(competition.signEndTime, '{y}/{m}/{d}') }}</span></div>
                    </div>
                    <div class='competition-info'>
                        <div class='competition-desc'><span>比赛介绍</span><img
                            src='@/assets/index/arrow-bottom.png'
                            alt='arrow'></div>
                        <div class='competition-desc-content'>
                            {{ competition?.description || '比赛介绍' }}
                        </div>
                    </div>
                    <div class='oper'>
                        <div class='btns'>


                            <!--参赛-->
                            <!--管理员或者评委 不展示-->
                            <template
                                v-if='
                                userStore?.userInfo.userId==1
                                ||
                                (competition.judgeIds?.length&&competition.judgeIds.includes(userStore?.userInfo.userId))'>
                            </template>
                            <template v-else>
                                <el-button
                                    v-if='signStatus&&publishStatus' disabled
                                    round type='primary'>已提交
                                </el-button>
                                <el-button
                                    v-else-if='signStatus' round type='primary'
                                    @click='submitCompetition'>提交作品
                                </el-button>
                                <el-button
                                    v-else round type='primary'
                                    @click='signCompetitionHandler'>报名比赛
                                </el-button>
                            </template>

                            <el-button
                                v-if='collectStatus'
                                round type='warning'
                                @click='collectCompetitionHandler'>
                                已收藏
                            </el-button>
                            <el-button
                                v-else round type='info'
                                @click='collectCompetitionHandler'>收藏比赛
                            </el-button>

                            <el-button round type='success' @click='onLookRank'>查看排名</el-button>
                        </div>
                        <div class='keywords'>
                            <el-form :mode='queryParams' @keydown.prevent.enter='queryHandler'>
                                <el-input
                                    v-model='queryParams.title' clearable placeholder='搜索作品...'
                                    @clear='clearHandler' />
                            </el-form>
                        </div>
                    </div>
                    <!--                    作品-->
                    <div v-if='works?.length' class='works'>
                        <div
                            v-for='work in works' :key='work.worksId' class='work'
                            @click='$router.push(`/worksDetail/${work.worksId}?judgeIds=${$route.query?.judgeIds}`)'>
                            <div class='cover'>
                                <img :src='`${coverArr[getRandomNumberInRange(0,1)]}`' alt='cover'>
                            </div>
                            <div class='work-info'>
                                <div class='works-title'>
                                    {{ work?.title || '作品标题' }}
                                </div>
                            </div>
                            <div class='other'>
                                <div class='user'>
                                    <div class='avatar'>
                                        <img v-if='work?.user?.avatar' :src='`/api${work?.user?.avatar}`' alt='avatar'>
                                        <img v-else src='@/assets/images/profile.jpg' alt='profile'>
                                    </div>
                                    <div class='nickname'>{{ work.user?.nickName || '作者名称' }}</div>
                                </div>
                                <div class='right-info'>
                                    <div>
                                        <img src='@/assets/index/look.png' alt='look'>
                                        <span>{{ handleCount(work?.views || 0) }}</span>
                                    </div>
                                    <div>
                                        <img src='@/assets/index/collect.png' alt='collect'>
                                        <span>{{ handleCount(work?.collect || 0) }}</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div v-else-if='!queryParams.title&&!works?.length' class='works empty'>
                        暂无作品,快来占领作品首座叭~
                    </div>
                    <div v-else-if='queryParams.title&&!works?.length&&queried' class='works empty'>
                        没有找到关键字[<span style='color: #E65D6E;'>{{ queryParams.title }}</span>]下的相关作品
                    </div>
                    <div v-else class='works empty'>
                        暂无作品,快来占领作品首座叭~
                    </div>
                    <!--分页-->
                    <div class='pagination'>
                        <pagination
                            v-show='total > 0'
                            v-model:limit='queryParams.pageSize'
                            v-model:page='queryParams.pageNum'
                            :total='total'
                            layout='total, prev, pager, next'
                            @pagination='getList'
                        />
                    </div>
                </div>
                <!--                评委-->
                <div class='right'>
                    <div class='title'>当前赛事评委</div>
                    <div v-if='competition?.judges?.length' class='judges'>
                        <div v-for='judge in competition?.judges||[]' :key='judge.userId' class='judge'>
                            <div class='judge-info'>
                                <div class='avatar'>
                                    <img v-if='judge.avatar' :src='`/api${judge.avatar}`' alt='avatar'>
                                    <img v-else src='@/assets/images/profile.jpg' alt='profile'>
                                </div>
                                <div class='nickname'>{{ judge?.nickName || '评委姓名' }}</div>
                            </div>
                            <div class='num'>{{ judge?.remark || '座右铭' }}</div>
                        </div>
                    </div>
                    <div v-else class='judges empty'>
                        该赛事暂未分配评委
                    </div>
                </div>
            </div>
        </div>
        <!--        提交作品-->
        <publishWorks v-model='open' :competitionId='competition.competitionId' @success='successHandler' />
        <!--    查看排名    -->
        <Rank v-model='openRank' :competitionId='competition.competitionId!' :competitionCover='competition.cover!'/>
        <!--        评论区域-->
        <div class='comment-container'>
            <!--            评论区主要展示区域-->
            <div class='comment-main-content'>
                <div class='comment-title'><span>评论区</span>
                </div>
                <template v-if='commentList.length'>
                    <div
                        v-for='comment in commentList'
                        :key='comment.commentId'
                        class='comment-box'>
                        <div class='top-header'>
                            <img
                                v-if='comment?.user?.avatar' class='avatar' :src='`/api${comment?.user?.avatar}`'
                                alt='avatar'>
                            <img v-else class='avatar' src='@/assets/images/profile.jpg' alt='avatar'>
                            <div class='comment-nickname-time'>
                                <div class='nickname'>{{ comment?.user?.nickName }}</div>
                                <div class='time'>
                                <span>{{ (formatTime(new Date(comment?.createTime).getTime(), '{y}-{m}-{d} {h}:{i}:{s}'))
                                    }}</span>·<span>{{ comment?.addr || '未知' }}</span></div>
                            </div>
                        </div>
                        <div class='comment-content'>
                            {{ comment.content }}
                        </div>
                        <div class='opers'>
                            <el-button type='primary' link class='reply' @click='replyHandler(comment)'>回复</el-button>
                            <el-button
                                v-if='comment.subTotal&&!comment.open' link
                                class='reply'
                                @click='openChildCommentHandler(comment )'><span
                                style='margin-right: 4px;'>展开{{ comment.subTotal }}条回复</span>
                                <el-icon>
                                    <ArrowDown />
                                </el-icon>
                            </el-button>
                        </div>
                        <!--                        2+n级评论-->
                        <div class='more-comments'>
                            <div class='sub-comments'>
                                <template v-if='comment.subComment?.length'>
                                    <div
                                        v-for='subComment in comment.subComment'
                                        :key='subComment.commentId' class='sub-comment-item'>
                                        <div class='sub-comment-header'>
                                            <img
                                                v-if='subComment?.user?.avatar' class='avatar'
                                                :src='`/api${subComment?.user?.avatar}`'
                                                alt='avatar'>
                                            <img v-else class='avatar' src='@/assets/images/profile.jpg' alt='avatar'>
                                            <div class='comment-nickname-time'>
                                                <div v-if='comment.commentId===subComment.parentId' class='nickname'>
                                                    {{ subComment?.user?.nickName }}
                                                </div>
                                                <div v-else class='nickname'>{{ subComment?.user?.nickName }}
                                                    <el-icon color='#CDD0D6'>
                                                        <CaretRight />
                                                    </el-icon>
                                                    {{ subComment?.receiveUser?.nickName }}
                                                </div>
                                                <div class='time'>
                                <span>{{ (formatTime(new Date(subComment?.createTime).getTime(), '{y}-{m}-{d} {h}:{i}:{s}'))
                                    }}</span>·<span>{{ subComment.addr }}</span></div>
                                            </div>
                                        </div>
                                        <div class='sub-comment-content'>
                                            {{ subComment.content }}
                                            <el-button
                                                style='margin-left: 10px;' type='primary'
                                                link class='reply' @click='replyHandler(subComment)'>
                                                回复
                                            </el-button>
                                        </div>


                                    </div>
                                </template>
                            </div>
                        </div>
                    </div>
                    <div v-if='commentList.length<commentTotal' class='comment-box more'>
                        <el-button link type='info' @click='moreLoadHandler'>加载更多</el-button>
                    </div>
                </template>

                <div v-else class='comment-box empty' style='min-height:350px;'>暂无评论,快来占个沙发叭~</div>
            </div>
            <!--            发布评论的区域-->
            <CommentPublish
                v-model:reply-info='replyInfo' :data-id='competition.competitionId'
                type='competition' @success='commentPublishSuccess' />
        </div>
    </div>
</template>
<script setup lang='ts'>
import { useRoute } from 'vue-router';
import type { Ref } from 'vue';
import { getCurrentInstance, reactive, ref, toRefs, watch } from 'vue';
import { addViews } from '@/api/business/brower';
import { Views } from '@/api/model/Views';
import { getCompetition, isSign, signCompetition } from '@/api/business/competition';
import { _Competition } from '@/api/model/Competition';
import { formatTime, getRandomNumberInRange, handleCount, parseTime, stopPageScroll } from '@/utils/sk';
import { Works } from '@/api/model/Works';
import { isPublish, listWorks } from '@/api/business/works';
import useUserStore from '@/store/modules/user';
import publishWorks from '@/components/JhPublishWorks/index.vue';
import Rank from '@/components/RankingList/index.vue';
import { isRelogin } from '@/utils/request';
import { collect, isCollect } from '@/api/business/collect';
import { listFirstComment, selectChildByRootId } from '@/api/business/comment';
import { _Comment } from '@/api/model/Comment';
import CommentPublish from '@/components/JhCommentPublish/index.vue';
import cover1 from '@/assets/default/cover/1.jpg';
import cover2 from '@/assets/default/cover/2.jpg';

const coverArr = ref([cover1, cover2]);
const open = ref(false);
const openRank = ref(false);
const userStore = useUserStore();
const queried = ref(false);
const { proxy } = getCurrentInstance();
const works: Ref<Works[]> = ref([]);
const route = useRoute();
const total = ref(0);
const commentTotal = ref(0);
const signStatus = ref(false);
const publishStatus = ref(false);
const collectStatus = ref(false);
const competition: Ref<_Competition> = ref({});
const commentList = ref<_Comment[]>([]);
const replyInfo = ref<{ nickName?: string, commentId?: number }>({});
/*请求参数定义*/
const data = reactive({
    form: {},
    rules: {
        content: [{
            required: true, message: '评论内容不能为空!', trigger: 'blur'
        }]
    },
    commentForm: {
        content: '',
        type: 'competition',
        dataId: -1
    },
    queryParams: { pageNum: 1, pageSize: 9, competitionId: -1, status: 1, title: '' },
    commentParams: {
        pageNum: 1, pageSize: 10, dataId: -1, type: 'competition'
    }
});
const { form, queryParams, commentForm, rules, commentParams } = toRefs(data);

//提交作品
const submitCompetition = () => {
    open.value = true;
    //停止页面滚动
    stopPageScroll();
};

//查看排名
const onLookRank = () => {
    openRank.value = true;
    //停止页面滚动
    stopPageScroll();
};


/*展开子集评论*/
const openChildCommentHandler = (comment: _Comment) => {
    const parentId = comment.commentId;//父级Id
    selectChildByRootId(parentId as number).then(res => {
        comment['subComment'] = res.rows;
        comment['open'] = true;
    });
};

/*回复*/
const replyHandler = (comment: _Comment) => {
    replyInfo.value = {
        commentId: comment.commentId,
        nickName: '@' + comment.user?.nickName.concat(' ')
    };
};
/*获取一级评论列表*/
const getFirstCommentList = async () => {
    commentParams.value.dataId = competition.value.competitionId || -1;
    await listFirstComment(commentParams.value).then(res => {
        res.rows.forEach((x: _Comment) => x.open = false);
        commentList.value = [...commentList.value, ...res.rows];
        commentTotal.value = res.total;
    });

};
/**
 * 加载更多评论
 */
const moreLoadHandler = () => {
    commentParams.value.pageNum += 1;
    getFirstCommentList();
};
/*评论/回复 成功回调 */
const commentPublishSuccess = async (commentId: number | null) => {
    commentParams.value.pageNum = 1;
    commentList.value = [];
    await getFirstCommentList();//获取评论
    const find = commentList.value.find(x => x.commentId === commentId);//查找父级
    if (find) {
        openChildCommentHandler(find);
    }
    replyInfo.value = {};
};
/*浏览比赛*/
const addViewsHandler = () => {
    const dataId = route.params?.competitionId;
    if (!dataId) return;
    const data: Views = {
        dataId: Number(dataId),
        type: 'competition'
    };
    addViews(data);
};
addViewsHandler();
/*获取比赛详细*/
const getCompetitionHandler = () => {
    const competitionId = route.params?.competitionId;
    if (!competitionId) return;
    getCompetition(competitionId as string).then(res => {
        competition.value = res.data;
        queryParams.value.competitionId = parseInt(competitionId as string);
        isSignHandler(parseInt(competitionId as string));/*获取比赛报名状态*/
        getList();/*获取作品列表*/
        isCollectHandler();/*获取比赛收藏状态*/
        getFirstCommentList();//获取评论
    });
};
getCompetitionHandler();
/*获取作品列表*/
const getList = () => {
    queryParams.value.competitionId = competition.value.competitionId!;
    if (!queryParams.value?.competitionId || queryParams.value.competitionId === -1) return proxy.$modal.msgError('获取比赛作品失败,比赛Id不存在!');
    /*获取作品*/
    listWorks(queryParams.value).then(res => {
        works.value = res.rows;
        total.value = res.total;
    });
};
/*查询*/
const queryHandler = () => {
    queryParams.value.pageNum = 1;
    queried.value = true;
    getList();
};
/*报名比赛*/
const signCompetitionHandler = () => {
    if (!userStore.isLogin) return isRelogin.show = true;
    const competitionId = route.params?.competitionId;
    if (!competitionId) return;
    signCompetition(competitionId as string).then(() => {
        proxy.$modal.msgSuccess('报名成功,请及时提交作品噢~');
        // isSignHandler(parseInt(competitionId as string));
        signStatus.value = true;
        open.value = true;
    });
};
/*获取比赛报名状态*/
const isSignHandler = (competitionId: number | string) => {
    if (!userStore.isLogin) return;
    if (!competitionId) return;
    isSign(competitionId).then(res => {
        signStatus.value = res.data;
        if (res.data) {
            isPublishHandler(competitionId);
        }
    });
};
/*获取作品提交状态*/
const isPublishHandler = (competitionId: number | string) => {
    if (!userStore.isLogin) return;
    if (!competitionId) return;
    isPublish(competitionId).then(res => {
        publishStatus.value = res.data;
    });
};
const successHandler = () => {
    open.value = false;
    signStatus.value = true;
    publishStatus.value = true;
};
/*清除*/
const clearHandler = () => {
    queryParams.value.pageNum = 1;
    queryParams.value.title = '';
    queried.value = false;
    getList();
};
/*收藏比赛*/
const collectCompetitionHandler = () => {
    if (!userStore.isLogin) return isRelogin.show = true;
    const competitionId = route.params.competitionId as string;
    if (!competitionId) return;
    /*收藏 取消收藏 并且获取收藏状态*/
    collect(competitionId, 'competition').then(() => isCollectHandler());
};
/**
 * 获取收藏状态
 */
const isCollectHandler = async () => {
    if (!userStore.isLogin) return;
    const competitionId = route.params.competitionId as string;
    if (!competitionId) return;
    isCollect(competitionId, 'competition').then(res => {
        collectStatus.value = res.data;
    });
};
watch(() => userStore.isLogin, () => {
    publishStatus.value = false;
    signStatus.value = false;
    collectStatus.value = false;
    // getCompetitionHandler();
    isSignHandler(route.params.competitionId as string);//报名状态
    isPublishHandler(route.params.competitionId as string);//作品提交状态
    isCollectHandler();//比赛收藏状态
    replyInfo.value = {};//回复人信息
});
</script>
<style scoped lang='scss'>
.more-comments {
    padding-left: 60px;
    margin-top: 10px;

    .nickname {
        color: rgba(0, 0, 0, 0.7);
        display: flex;
        align-items: center;
        margin-bottom: 4px;

        i {
            margin: 0 6px;
        }
    }

    .sub-comment-item {
        margin-top: 10px;

        &.my-comment {
            .sub-comment-header {
                justify-content: flex-end;
            }

            .sub-comment-content {
                text-align: right;

            }
        }
    }

    .avatar {
        width: 30px;
        height: 30px;
        border-radius: 50%;
        object-fit: cover;
        margin-right: 10px;
    }

    .sub-comment-content {
        padding-left: 40px;
        font-size: 16px;
        display: flex;
        align-items: center;
        margin-top: 10px;
    }

    .sub-comment-header {
        display: flex;
        color: rgba(0, 0, 0, 0.5);
        align-items: center;


    }

    .comment-nickname-time {
        font-size: 12px;
    }
}

.comment-container {
    margin-top: 20px;
    //padding: 0 670px 0 250px;
    padding: 0 250px;
    display: flex;
    position: relative;
    align-items: flex-start;


    .comment-main-content {
        width: 1000px;
        border-radius: 4px;
        margin-right: 20px;
    }

    .comment-title {
        font-size: 20px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 20px;
    }

    .top-header {
        display: flex;
        color: rgba(0, 0, 0, 0.5);

        .comment-nickname-time {
            display: flex;
            flex-direction: column;
            justify-content: space-between;

            .nickname {
                color: rgba(0, 0, 0, 0.7);
            }

            .time {
                font-size: 14px;
            }
        }

        .avatar {
            width: 50px;
            height: 50px;
            object-fit: cover;
            border-radius: 50%;
            margin-right: 10px;
        }
    }

    .comment-content {
        padding-left: 60px;
        margin-top: 10px;
        //padding-right: calc(50% - 20px);
        font-size: 18px;
    }

    .opers {
        display: flex;
        flex-direction: column;
        align-items: flex-start;

        .reply {
            padding-left: 60px;
            margin: 5px 0;
        }
    }

    .comment-box {
        background: #fff;
        border-radius: 4px;
        padding: 20px;
        border-bottom: 1px #efefef solid;

        &.more {
            text-align: center;
        }

        &.my-comment {
            .top-header {
                justify-content: flex-end;
            }

            .comment-content {
                text-align: right;
                padding-left: calc(50% - 20px);
                padding-right: 60px;
            }

            .opers {
                align-items: flex-end;
            }

            .avatar {
                order: 2;
                margin-right: 0;
                margin-left: 10px;
            }

            .comment-nickname-time {
                order: 1;
                align-items: flex-end
            }
        }
    }

}

.competition-detail {

    .cover {
        height: 350px;

        img {
            height: 100%;
            width: 100%;
            object-fit: cover;
        }
    }

    .content-main {
        padding: 0 250px;
    }

    .crumbs {
        display: flex;
        align-items: center;
        margin: 20px 0;

    }

    .competition-detail-content {
        display: flex;
        align-items: flex-start;

        .left, .right {
            border-radius: 6px;
            background: #FFFFFF;
        }

        .left {
            width: 1000px;
            border-radius: 4px;
            margin-right: 20px;
            padding: 20px;

            .title {
                font-size: 22px;
                font-weight: 700;
                color: rgba(0, 0, 0, 0.8);
                text-align: center;
            }

            .icons {
                display: flex;
                align-items: center;
                justify-content: center;
                margin: 20px 0;

                .icon {
                    font-size: 16px;
                    font-weight: 400;
                    color: rgba(0, 0, 0, 0.7);
                    margin-right: 40px;

                    &.date {
                        margin-right: 20px;
                        display: flex;
                        align-items: center;

                        span:last-child {
                            padding: 5px 10px;
                            background: rgba(64, 158, 255, 0.8);
                            border-radius: 4px;
                            color: #fff;
                        }
                    }

                    span:first-child {
                        margin-right: 4px;
                        color: rgba(0, 0, 0, 0.8);
                    }
                }
            }
        }

        .right {
            flex: 1;
            overflow: hidden;
            position: sticky;
            top: 10px;

            .title {
                padding: 17px 0;
                background: rgba(64, 158, 255, 0.8);
                font-size: 20px;
                font-weight: 500;
                color: #FFFFFF;
                text-align: center;
            }
        }

        .judges {
            padding: 20px;

            .judge {
                display: flex;
                align-items: center;
                justify-content: space-between;
                margin-bottom: 20px;

                .num {
                    font-size: 16px;
                    font-weight: 400;
                    color: rgba(0, 0, 0, 0.5);
                    @include ellipsisOption(1);
                }
            }

            .judge-info {
                display: flex;
                align-items: center;
                width: 250px;
            }

            .nickname {
                font-size: 20px;
                font-weight: 500;
                color: #3D3D3D;
                margin-left: 10px;
            }

            .avatar {
                width: 60px;
                height: 60px;
                border-radius: 4px;
                overflow: hidden;

                img {
                    width: 100%;
                    height: 100%;
                }
            }
        }
    }

    .competition-info {
        .competition-desc {
            display: flex;
            align-items: center;
            cursor: pointer;
            font-size: 18px;
            font-weight: 400;
            color: rgba(0, 0, 0, 0.8);
            width: fit-content;

            img {
                margin-left: 5px;
            }
        }

        .competition-desc-content {
            margin-top: 10px;
            font-size: 16px;
            font-weight: 400;
            color: rgba(0, 0, 0, 0.8);
        }
    }

    .oper {
        padding: 10px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        background: #F2F6FC;
        margin: 20px 0;

        .keywords {
            width: 250px;
        }
    }

    .works {
        display: flex;
        flex-wrap: wrap;
        min-height: 280px;


        .work {
            overflow: hidden;
            padding: 10px;
            width: 300px;
            min-height: 270px;
            background: #F2F6FC;
            border-radius: 4px;
            margin-right: 30px;
            margin-bottom: 20px;
            transition: 0.3s;
            cursor: pointer;

            &:hover {
                box-shadow: var(--el-box-shadow);
            }

            &:nth-child(3n) {
                margin-right: 0;
            }
        }

        .cover {
            border-radius: 4px;
            height: 150px;
            overflow: hidden;
            margin-bottom: 10px;

            img {
                height: 100%;
                width: 100%;
                object-fit: cover;
            }
        }

        .other {
            margin-top: 14px;
            align-items: center;
            display: flex;
            justify-content: space-between;
        }

        .user {
            display: flex;
            align-items: center;

            .nickname {
                font-size: 14px;
                font-weight: 400;
                color: #000000;
            }

            .avatar {
                width: 35px;
                height: 35px;
                border-radius: 50%;
                overflow: hidden;
                margin-right: 10px;

                img {
                    width: 100%;
                    height: 100%;
                    object-fit: cover;
                }
            }
        }

        .right-info {
            display: flex;
            align-items: center;

            div {
                display: flex;
                align-items: center;
                margin-left: 20px;

                img {
                    margin-right: 5px;
                }
            }
        }

        .works-title {
            font-size: 16px;
            font-weight: 400;
            color: rgba(0, 0, 0, 0.8);
            @include ellipsisOption(2);
        }
    }
}
</style>
